# -*- coding: utf-8 -*-
# @Author: wujiyu
# @Date:   2017-02-26 22:49:03
# @Last Modified by:   wujiyu
# @Last Modified time: 2017-03-27 12:25:07
import requests
import logging
# requests.packages.urllib3.disable_warnings()

import datetime

from util.configutil import ConfigUtil
from util.mylog import install_log, info, critical
from util.cookie_util import has_cookies
from util.date_util import DateUtil
from util.utils import clear_output

import schedule
from src.meican import MeiCan
import time
import traceback
from util.ToastNotifier import ToastNotifier
import win32api
import win32con
import os, sys
from util.cookie_util import save_auto_run

toaster = ToastNotifier()


def order(meican, try_count):
    try:
        order_week = ConfigUtil.instance().order_week
        cur_week = str(DateUtil.curr_week())
        if cur_week not in order_week:
            critical("meican | order week not in config!!!!!!!!!!!!, cur_week:<%s>" % cur_week)
            return
        info("meican |begin order")
        meican.order()
    except Exception as e:
        try_count += 1
        critical(F'第{try_count}次尝试重新点餐')
        if try_count == 50:
            info(traceback.format_exc())
            return
        time.sleep(1)
        order(meican, try_count + 1)


def do_job():
    try:
        info("I'm working on : <%s>" % datetime.datetime.now())
    except Exception as e:
        info(traceback.format_exc())


def do_main():
    info("start meican robot")

    meican = None
    login_ok = False
    if has_cookies():
        meican = MeiCan('', '')
        login_ok = meican.login()
    else:
        while not login_ok:
            username = input('[ Enter meican email ]:')
            password = input('[ Enter meican password ]:')
            meican = MeiCan(username, password)
            login_ok = meican.login()
        clear_output()
    limit_lst = meican.get_order_time_lst()
    meican.order()
    for time_item in limit_lst:
        time_str = "%s:%s" % (time_item.hour, time_item.minute)
        #time_str = '15:10'
        schedule.every(1).day.at(time_str).do(order, meican, 1)
    info("meican | next order time: | [[%s]]" % schedule.next_run())
    if login_ok:
        toaster.show_toast(
            "美餐自动定餐服务",
            "登录成功| next order time: | [%s]" % schedule.next_run(),
            duration=300)

    # schedule.every(1).hour.do(do_job)
    while True:
        schedule.run_pending()
        time.sleep(1)


def auto_run():
    # zdynames = os.path.basename(__file__)  # 当前文件名的名称如：newsxiao.py
    # name = os.path.splitext(zdynames)[0]  # 获得文件名的前部分,如：newsxiao
    abspath = os.path.abspath(os.path.dirname(__file__))
    auto_run_name = 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\autoRunMeican.bat'
    save_auto_run(abspath, auto_run_name)

    print("自动开机启动-添加成功！- %s" % auto_run_name)


if __name__ == '__main__':
    try:
        install_log()
        #auto_run()
        do_main()
    except Exception as e:
        print("OS error: {0}".format(traceback.format_exc()))
    input()
